import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../view/Login.vue'
import Register from '../view/Register.vue'
import Home from '../view/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/Users.vue'
import Role from '../components/Role.vue'
import Back from '../components/Back.vue'
import Orders from '@/components/Orders.vue'
import Report from '@/components/Report.vue'
import Fault from '@/components/Fault.vue'
import My from '@/components/My.vue'
// const Login = () =>
//     import ( /* webpackChunkName: "login_home_welcome_register" */ '../view/Login.vue')

Vue.use(VueRouter)

const routes = [
    // 重定向
    { path: '/', redirect: '/login' },
    // 登录
    { path: '/login', component: Login },
    // 注册
    { name: 'register', path: '/register', component: Register },
    // 首页
    {
        name: 'home',
        path: '/home',
        component: Home,
        redirect: '/welcome',
        // 主体部分路由
        children: [
            { name: 'welcome', path: '/welcome', component: Welcome },
            { name: 'users', path: '/users', component: Users },
            { name: 'roles', path: '/roles', component: Role },
            { name: 'back', path: '/back', component: Back },
            { name: 'orders', path: '/orders', component: Orders },
            { name: 'reports', path: '/reports', component: Report },
            { name: 'fault', path: '/fault', component: Fault },
            { name: 'my', path: '/my', component: My }
        ]
    }
]

const router = new VueRouter({
    routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
    if (to.path === '/login') return next()
    if (to.path === '/register') return next()
    if (to.path === '/home' || to.path === '/welcome') {
        // 判断是否登录
        const token = window.sessionStorage.getItem('token')
            // console.log('token', token)
        if (!token) {
            // 直接访问则强制跳转至登录界面
            Vue.prototype.$message.error('请先登录才可以访问哦！')
            return next('/login')
        } else {
            // 放行
            return next()
        }
    }
    return next()
})

export default router